"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : DDL-function
Case Name   : 函数调用导致日志膨胀问题
Create At   : 2023/04/03
Owner       : @kyeleze
Description :
    1.创建函数
    2.执行函数
    3.查看pg_log日志
Expect      :
    1.成功
    2.成功
    3.未检测到有关该函数的信息
History     :
"""
import os
import unittest

from yat.test import macro
from yat.test import Node

from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class CreateFunction(unittest.TestCase):
    def setUp(self):
        self.logger = Logger()
        self.logger.info(f'----{os.path.dirname(__file__)} start----')
        self.primary_sh = CommonSH('PrimaryDbUser')
        self.primary_node = Node('PrimaryDbUser')
        self.constant = Constant()
        self.function_name = 'f_ddl_create_fun_0159'

    def test_create_function(self):
        step = '--step1:创建函数 expect:成功--'
        self.logger.info(step)
        sql_cmd = f'create or replace function {self.function_name} (a text) ' \
                  f'return int ' \
                  f'is begin return 1; end;'
        self.logger.info(sql_cmd)
        result = self.primary_sh.execut_db_sql(sql_cmd)
        self.logger.info(result)
        self.assertIn(self.constant.CREATE_FUNCTION_SUCCESS_MSG,
                       result, '执行失败' + step)

        step = '--step2:执行函数 expect:成功--'
        self.logger.info(step)
        result = self.primary_sh.execut_db_sql(f"select "
                                               f"{self.function_name}('x');")
        self.logger.info(result)
        self.assertIn('1 row', result, '执行失败' + step)

        step = '--step3:查看pg_log日志 expect:未检测到有关该函数的信息--'
        self.logger.info(step)
        cmd = f"grep -r '{self.function_name}' {macro.PG_LOG_PATH}/*"
        result = self.primary_node.sh(cmd).result()
        self.logger.info(result)
        self.assertEqual('', result, '执行失败' + step)

    def tearDown(self):
        step = '--清理环境--'
        self.logger.info(step)
        result = self.primary_sh.execut_db_sql(f'drop function '
                                               f'{self.function_name};')
        self.logger.info(result)
        self.assertIn(self.constant.DROP_FUNCTION_SUCCESS_MSG,
                      result, '执行失败' + step)
        self.logger.info(f'----{os.path.dirname(__file__)} end----')

